package org.mspring.mlog.web.task.comment;

import java.util.HashMap;
import java.util.Map;

import org.mspring.mlog.entity.Comment;
import org.mspring.mlog.entity.Post;
import org.mspring.mlog.service.PostService;
import org.mspring.mlog.utils.PostUrlUtils;
import org.mspring.platform.config.ConfigService;
import org.mspring.platform.mail.MailService;
import org.mspring.platform.task.AbstractTask;
import org.mspring.platform.utils.FreemarkerUtils;
import org.mspring.platform.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import freemarker.template.Configuration;

/**
 *
 * @since 2014-04-10 15:00:36
 * @author Gao Youbo
 */
@Component
public class CommentNoticeTask extends AbstractTask {

    private static final Logger log = LoggerFactory.getLogger(CommentNoticeTask.class);

    private static final String FTL = "/mail/comment_notice.ftl";

    @Autowired
    private ConfigService configService;
    @Autowired
    private MailService mailService;
    @Autowired
    private PostService postService;
    @Autowired
    private Configuration configuration;

    @Override
    protected void doTask(Map<Object, Object> paramMap) throws Exception {
        Comment comment = (Comment) paramMap.get("comment");
        if (comment == null) {
            return;
        }
        String commentUrl = PostUrlUtils.getPostAbsUrl(comment.getPost().getId());
        Post post = null;
        if (comment.getPost() == null || comment.getPost().getId() == null) {
            log.warn("未找到评论对应的文章, comment={}", comment.getId());
            return;
        }
        post = this.postService.get(comment.getPost().getId());
        if (post == null) {
            log.warn("未找到评论对应的文章, comment={}, post={}", comment.getId(), comment.getPost().getId());
            return;
        }
        String to = post.getAuthor().getEmail();
        String personal = post.getAuthor().getAlias();
        if (StringUtils.isBlank(to)) {
            log.warn("未找到收件人邮箱, post={}", post.getId());
            return;
        }
        if (StringUtils.isBlank(personal)) {
            personal = "用户";
        }
        Map<Object, Object> model = new HashMap<>();
        model.put("commentUrl", commentUrl);
        model.put("comment", comment);
        model.put("post", post);
        String content = FreemarkerUtils.render(this.configuration, FTL, model);
        String subject = configService.getConfig("sitename") + " - <".concat(post.getTitle()).concat("> - 评论通知");
        if (StringUtils.isBlank(content)) {
            log.warn("内容不能为空.");
            return;
        }
        mailService.sendMail(to, personal, subject, content);
    }

}
